import {NextRequest, NextResponse} from "next/server";
import fs from "fs/promises";
import path from "path";
import {RecordProps, RecordsRequestProps, RecordsResponseProps} from "./interface";

export async function POST(request: NextRequest) {
  try {
    // 解析请求体
    const {page = 1, pageSize = 10}: RecordsRequestProps = await request.json();

    // 读取数据文件，文件存放位置：/public/mock/simuProj.json
    const filePath = path.join(process.cwd(), "public", "mock", "simuPlan.json");
    const data = await fs.readFile(filePath, "utf-8");
    const records: RecordProps[] = JSON.parse(data);

    // 分页逻辑
    const totalRecords = records.length; // 总记录数
    const startIndex = (page - 1) * pageSize;
    const paginatedRecords = records.slice(startIndex, startIndex + pageSize);

    // 返回数据，确保符合 FetchResponse 格式
    const response: RecordsResponseProps = {
      totalRecords,
      records: paginatedRecords,
    };
    console.log(response);

    // 返回分页数据
    return NextResponse.json(response);
  } catch (error) {
    console.log("error");
    return NextResponse.json({error: "获取数据失败"}, {status: 500});
  }
}
